package com.beiwei.controller;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beiwei.auto.mode.Department;
import com.beiwei.auto.mode.Job;
import com.beiwei.auto.mode.User;
import com.beiwei.auto.mode.Weeklog;
import com.beiwei.mode.VDepartment;
import com.beiwei.mode.VWeeklog;
import com.beiwei.service.DepartmentService;
import com.beiwei.service.GroupService;
import com.beiwei.service.JobService;
import com.beiwei.service.UserService;
import com.beiwei.service.WeeklogService;
import com.github.pagehelper.Page;

@Controller
@RequestMapping("/weeklog")
public class WeeklogHandler {

	@Autowired
	private WeeklogService weeklogService;

	@Autowired
	private UserService userService;

	@Autowired
	private JobService jobService;

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private GroupService groupService;

	/**
	 * 我的周报列表(分页)
	 */
	@RequestMapping("/myself/{pageNum}/{pageCount}")
	public String myWeeklog(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageCount") Integer pageCount, Model model) {
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User) currentUser.getPrincipal();

		Page<Weeklog> page = null;
		User leadUser = null;
		Job job = null;
		Department department = null;

		try {
			page = weeklogService.findWeeklogListByUserId(user.getUserId(), pageNum, pageCount);
			// weeklogs =
			// weeklogService.findWeeklogListByUserId(user.getUserId());
			leadUser = userService.findUserByUserId(user.getLeadId());
			job = jobService.findJobByJobId(user.getUserJobId());

			department = (job == null) ? null : departmentService.findDepartmentByDepartmentId(job.getJobDepartmentId());

		} catch (Exception e) {
			e.printStackTrace();
		}

		model.addAttribute("total", page.getTotal());// 总条数
		model.addAttribute("pageSize", page.getPageSize());// 每页的总容量
		model.addAttribute("pageNum", page.getPageNum());
		model.addAttribute("weeklogs", page);

		model.addAttribute("leadUser", leadUser);
		model.addAttribute("job", job);
		model.addAttribute("department", department);

		return "myWeeklogList";
	}

	/**
	 * 保存周报
	 */
	@RequestMapping(value = "/save", method = RequestMethod.PUT, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String editSave(VWeeklog weeklog) {
		try {
			if (weeklogService.updateVWeeklog(weeklog)) {
				return "success";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "操作失败";
	}

	/**
	 * 查询周报 type:1时，为普通查询。2时为周报管理员查询只可以修改上级评分
	 */
	@RequestMapping(value = "/edit/{type}/{weeklogId}", method = RequestMethod.GET)
	public String edit(@PathVariable("type") Integer type, @PathVariable("weeklogId") Integer weeklogId, Model model) {
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User) currentUser.getPrincipal();

		VWeeklog vWeeklog = null;
		User leadUser = null;
		Job job = null;
		Department department = null;
		Date endtime = null;

		try {
			vWeeklog = weeklogService.findVWeeklogByWeeklogId(weeklogId);
			System.out.println(vWeeklog);
			leadUser = userService.findUserByUserId(user.getLeadId());
			job = jobService.findJobByJobId(user.getUserJobId());
			department = (job == null) ? null : departmentService.findDepartmentByDepartmentId(job.getJobDepartmentId());

			// 获取结束时间（即为：创建时间+6）
			GregorianCalendar gc = new GregorianCalendar();
			gc.setTime(vWeeklog.getCreatetime());
			/*
			 * *java中对日期的加减操作gc.add(1,-1)表示年份减一.gc.add(2,-1)表示月份减一.
			 * gc.add(3.-1)表示周减一.gc.add(5,-1)表示天减一.
			 */
			gc.add(5, +6);
			endtime = gc.getTime();

		} catch (Exception e) {
			e.printStackTrace();
		}

		model.addAttribute("weeklog", vWeeklog);
		model.addAttribute("leadUser", leadUser);
		model.addAttribute("job", job);
		model.addAttribute("department", department);
		model.addAttribute("endtime", endtime);

		if (type == 2 && currentUser.isPermitted("weeklog:update")) {
			return "gradeWeeklog2";
		}
		return "editWeeklog";
	}

	/**
	 * 周报管理
	 */
	@RequestMapping("/groupWeeklogs/{departmentId}/{groupId}")
	@RequiresPermissions("weeklog:update")
	public String groupWeeklogs(@PathVariable("departmentId") Integer departmentId, @PathVariable("groupId") Integer groupId, Model model) {
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User) currentUser.getPrincipal();

		int groupSum = 0;
		Job job = null;
		List<VWeeklog> weeklogs = null;
		Department department = null;
		List<VDepartment> vDepartments = null;

		try {
			groupSum = groupService.getCount();
			if (groupId == 0) {
				// 默认查询出最后一组周报
				groupId = groupSum;
			}
			job = jobService.findJobByJobId(user.getUserJobId());
			if (departmentId == 0) {
				departmentId = job.getJobDepartmentId();
			}
			
			weeklogs = (job == null) ? null : weeklogService.findVWeeklogListByDepartmentIdAndGroupId(departmentId, groupId);
			department = departmentService.findDepartmentByDepartmentId(job.getJobDepartmentId());
			vDepartments = departmentService.findVDepartmentListByCompanyId(user.getUserCompanyId());
		} catch (Exception e) {
			e.printStackTrace();
		}

		model.addAttribute("department", department);
		model.addAttribute("vDepartments", vDepartments);
		model.addAttribute("departmentId", departmentId);
		model.addAttribute("job", job);
		model.addAttribute("weeklogs", weeklogs);
		model.addAttribute("groupSum", groupSum);
		model.addAttribute("groupId", groupId);

		return "groupWeeklogList";
	}

}
